// 购物车数据结构
let cart = JSON.parse(localStorage.getItem('cart')) || [];

// 打开/关闭购物车
function toggleCart() {
    const modal = document.querySelector('.cart-modal');
    const overlay = document.querySelector('.overlay');

    modal.classList.toggle('active');
    overlay.classList.toggle('active');

    updateCartDisplay();
}

// 初始化遮罩点击事件
document.addEventListener('DOMContentLoaded', () => {
    const overlay = document.createElement('div');
    overlay.className = 'overlay';
    overlay.onclick = toggleCart;
    document.body.appendChild(overlay);
});

// 添加商品到购物车
function addToCart(item) {
    const existing = cart.find(i =>
        i.id === item.id && i.type === item.type
    );

    if (existing) {
        existing.quantity += item.quantity;
    } else {
        cart.push({...item});
    }

    saveCart();
    updateCartIcon();
}

// 更新本地存储
function saveCart() {
    localStorage.setItem('cart', JSON.stringify(cart));
}

// 更新购物车图标数量
function updateCartIcon() {
    const count = cart.reduce((sum, item) => sum + item.quantity, 0);
    document.getElementById('cartCount').textContent = count;
}

function cleanCartIcon() {
    const count = 0
    document.getElementById('cartCount').textContent = count;
}

// 渲染购物车列表
function updateCartDisplay() {
    const container = document.getElementById('cartItems');
    const total = cart.reduce((sum, item) =>
        sum + (item.price * item.quantity), 0);

    container.innerHTML = cart.map(item => `
        <div class="cart-item">
            <div class="item-image">
                <img src="${item.imgUrl || '/images/default-product.jpg'}" 
                     alt="${item.name}">
            </div>
            <div class="item-info">
                <div class="item-title">${item.name}</div>
                <div class="item-price">¥ ${item.price.toFixed(2)}</div>
                <div class="quantity-control">
                    <button class="quantity-btn" 
                            onclick="updateQuantity('${item.type}', '${item.id}', -1)">-</button>
                    <input type="number" 
                           class="quantity-input" 
                           value="${item.quantity}"
                           min="1"
                           onchange="updateQuantity('${item.type}', '${item.id}', 0, this.value)">
                    <button class="quantity-btn" 
                            onclick="updateQuantity('${item.type}', '${item.id}', 1)">+</button>
                    <span class="remove-btn" 
                          onclick="removeItem('${item.type}', '${item.id}')">删除</span>
                </div>
            </div>
        </div>
    `).join('');

    document.getElementById('totalAmount').textContent = total.toFixed(2);
}

// 修改数量
function updateQuantity(type, id, delta, newVal) {
    const item = cart.find(i => i.type === type && i.id === id);
    if (!item) return;

    if (newVal !== undefined) {
        item.quantity = parseInt(newVal) || 1;
    } else {
        item.quantity = Math.max(1, item.quantity + delta);
    }

    saveCart();
    updateCartDisplay();
    updateCartIcon();
}

// 删除商品
function removeItem(type, id) {
    cart = cart.filter(i => !(i.type === type && i.id === id));
    saveCart();
    updateCartDisplay();
    updateCartIcon();
}

// 支付处理
async function handleCheckout() {
    if (cart.length === 0) {
        alert('购物车为空！');
        return;
    }

    const payload = {
        shoppingDTOList: cart.map(item => ({
            proType: item.type === 'product' ? 0 : 1,
            id: item.id,
            quantity: item.quantity
        }))
    };

    try {
        const response = await fetch('/system/shopping/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload)
        });

        const result = await response.json();
        if (result.code === 0) {
            showSuccessModal('支付成功！'); // 使用弹窗提示
            cart = [];
            saveCart();
            toggleCart();
            cleanCartIcon();
        } else {
            showErrorModal('支付失败：' + result.msg);
        }
    } catch (error) {
        showErrorModal('网络错误，请稍后重试');
        console.error('支付请求失败:', error);
    }
}

// 显示成功弹窗
function showSuccessModal(message) {
    const modal = document.createElement('div');
    modal.className = 'success-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <span class="close-btn" onclick="this.parentElement.parentElement.remove()">&times;</span>
            <h3>🎉 ${message}</h3>
        </div>
    `;
    document.body.appendChild(modal);
}

// 显示错误弹窗
function showErrorModal(message) {
    const modal = document.createElement('div');
    modal.className = 'error-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <span class="close-btn" onclick="this.parentElement.parentElement.remove()">&times;</span>
            <h3>❌ ${message}</h3>
        </div>
    `;
    document.body.appendChild(modal);
}

// 初始化购物车图标
updateCartIcon();